
#ifndef __H_CONNECTION_H__
#define __H_CONNECTION_H__

#include "linux_def.h"
#include "core.h"
#include "os.h"
/*
#define PEER_KEEPALIVE	1
#define PEER_NEXT	2
#define PEER_FAILED	4
*/

typedef struct listening_s	listening_t;

struct listening_s{
	int	fd;
	struct sockaddr *sockaddr;
	socklen_t	socklen;

	int	family;
	int	type;
	int	backlog;
	int	rcvbuf;
	int	sndbuf;

	connection_handler_pt handler;

	connection_t	*connection;
	int		post_accept_timeout;

	pool_t	*pool;
	log_t	*log;

	size_t		pool_size;
	unsigned	open:1;
	unsigned	ignore:1;
	unsigned	bound:1;
	unsigned	listen:1;
	unsigned	nonblocking:1;
};

struct connection_s{
	int		fd;
	void		*data;
	event_t		*read;
	event_t		*write;

	recv_pt		recv;
	send_pt		send;
	recv_chain_pt	recv_chain;
	send_chain_pt	send_chain;
	
	connection_t	*connection;
	struct sockaddr	*sockaddr;
	socklen_t	socklen;
	
	listening_t	*listening;
	
	unsigned	timedout:1;
	unsigned	idle:1;
	unsigned	close:1;

	char		*buf;
	
	int		number;

#if (THREADS)
//	atomic_t		*lock;
#endif

	pool_t		*pool;
	log_t		*log;
};

typedef struct{
	pool_t	*pool;
	int	start_sec;
	int	start_msec;
}request_time;

int open_listening_sockets(cycle_t *cycle);
void configure_listening_sockets(cycle_t *cycle);
void close_listening_sockets(cycle_t *cycle);

void init_connection(connection_t *);
connection_t *get_connection(int fd);
void free_connection(connection_t *c);
void close_connection(connection_t *c);

#endif
